
import { useUi } from "/$/cool-ui";
import { storage } from "/@/cool/utils";
import { useCool } from "/@/cool";
import { reactive } from "vue";
import { isAdvertising, rewardedFunction, rewardedFunctionItem } from "./rewarded";
const ui = useUi();
let audioManager = reactive({})
export const tencentUrl = "https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/mp3/"
// #ifndef WEB
audioManager = uni.getBackgroundAudioManager()
audioManager.onEnded(endCommonFunction)
audioManager.onPause((res) => {
	audioManagerObj.musicValue = ""
	audioManagerObj.musicValueArr = []
	audioManagerObj.musicCurrent = 0
	audioManagerObj.isPlay = false
	clearTimeout(audioManagerObj.bgAudioTime)
	audioManagerObj.bgAudioTime = 0
})
audioManager.onPlay((res) => {
	audioManagerObj.isPlay = true
})
audioManager.onError((res) => {
	console.log(res, 1)
})
audioManager.onStop((res) => {
	console.log('stop', 1)
	audioManagerObj.isPlay = false
	clearTimeout(audioManagerObj.bgAudioTime)
	audioManagerObj.bgAudioTime = 0
})
//#endif
audioManager.title = '象数助念器';
audioManager.singer = '暂无';
audioManager.coverImgUrl = 'https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/wechat_option/logo.png';
export const audioManagerObj = reactive({
	speed: storage.get('speed') ? storage.get('speed') : 1,
	isPlay: false, //是否正在播放
	musicCurrent: 0, //正在播放的下标
	musicValueArr: [] as any, //播放的数组
	bgAudioTime: 0, //定时器
	showAudioTime: 1,//小组件定时器
	playId: "",//当前播放的id
	sexual: storage.get('sexual') ? storage.get('sexual') : 'nan', //男/女声音切换
	musicValue: "",//播放的字符串
	x: "",//播放小组件的坐标
	y: "",
	showAudio: false,
	playSrc: "",//微信正在播放的音频链接
	nanPlaySrc: "",//微信男的音频链接
	nvPlaySrc: "",//微信女的音频链接
	preValue: "",//上一个播放的象数
})

// 音频结束事件
function endCommonFunction() {
	mpWxEndFunction()
	//// #ifdef APP
	//appEndFunction()
	//// #endif
	//// #ifdef MP-WEIXIN
	//mpWxEndFunction()
	//// #endif
}
// 切换倍速
export function changeSlider(res) {
	audioManager.playbackRate = res.detail.value
	audioManagerObj.speed = res.detail.value
	storage.set('speed', res.detail.value)
}
// 微信播放结束事件
function mpWxEndFunction() {
	let src = audioManagerObj.sexual == 'nv' ? audioManagerObj.nvPlaySrc : audioManagerObj.nanPlaySrc
	audioManager.src = src
}
// app播放结束事件
function appEndFunction() {
	if (audioManagerObj.isPlay) {
		// 如果说当前播放的下标大于等于整个数组,就重置下标
		if (audioManagerObj.musicCurrent >= audioManagerObj.musicValueArr.length) {
			audioManagerObj.musicCurrent = 0
		}
		if (audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == '·' || audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == '.') {
			let number : number = getDropNumber()
			audioManagerObj.bgAudioTime = setTimeout(() => {
				audioManagerObj.musicCurrent = audioManagerObj.musicCurrent + number
				if (audioManagerObj.musicCurrent >= audioManagerObj.musicValueArr.length) {
					audioManagerObj.musicCurrent = 0
				}
				// 防止第一个数与最后一个数相同
				if (audioManagerObj.musicCurrent == 0 && audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == audioManagerObj.musicValueArr[audioManagerObj.musicValueArr.length - 2]) {
					audioManager.seek(0)
					audioManager.play()
				} else {
					music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
				}

				audioManagerObj.musicCurrent++
			}, number * 1000);
		} else {
			// 如果上一个数和这个数相同
			if (audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == audioManagerObj.musicValueArr[audioManagerObj.musicCurrent - 1]) {
				audioManager.seek(0)
				audioManager.play()
			} else {
				// 防止第一个数与最后一个数相同
				if (audioManagerObj.musicCurrent == 0 && audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == audioManagerObj.musicValueArr[audioManagerObj.musicValueArr.length - 2]) {
					audioManager.seek(0)
					audioManager.play()
				} else {
					music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
				}
				// music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
			}
			audioManagerObj.musicCurrent++
		}
	}
}
// 获取连续点的数量
function getDropNumber() {
	let number = 0
	for (let i = audioManagerObj.musicCurrent; i < audioManagerObj.musicValueArr.length; i++) {
		if (audioManagerObj.musicValueArr[i] == '.' || audioManagerObj.musicValueArr[i] == '·') {
			number++
		} else {
			return number
		}
	}
	return number
}
//获取网络状态
export function getNetworkType() {
	return new Promise(async (resolve, reject) => {
		uni.getNetworkType({
			success(res) {
				if (res.networkType == 'none' || res.networkType == 'unknown') {
					resolve(false)
				} else {
					resolve(true)
				}
			}
		});
	})
}
// 点击播放
export async function playMusic() {
	stopListening()
	//// #ifdef APP
	//appPlayMusic()
	//// #endif
	//// #ifdef MP-WEIXIN
	mpWxPlayMusic()
	//// #endif
}
// 微信小程序播放音频
async function mpWxPlayMusic() {
	// 如果正在播放，就暂停
	if (audioManagerObj.isPlay) {
		audioManager.pause()
		audioManagerObj.isPlay = false
	} else {
		// 播放广告
		rewardedFunction.value = 'adMpWxPlayMusic'
		let isAd = await isAdvertising()
		if (isAd == 0 || isAd == 2) {
			return
		}
		adMpWxPlayMusic()
	}
}
export async function adMpWxPlayMusic() {
	rewardedFunction.value = ""
	// 如果有链接就直接播放
	if (audioManagerObj.preValue && audioManagerObj.musicValue == '') {
		if (audioManagerObj.nanPlaySrc) {
			audioManager.play()
			audioManagerObj.isPlay = true
		}
		return
	}
	if (audioManagerObj.musicValue == "") {
		ui.showToast("没有正在播放的");
		return
	}
	// 如果没在播放 musicValue也没值，代表暂停,继续播放
	if (audioManagerObj.musicValue == "") {
		audioManager.play()
	} else {
		// 如果musicValue有值，代表新修改的数字，要从头播放
		if (audioManagerObj.musicValue.length < 2) {
			ui.showToast("至少输入两位象数");
			audioManagerObj.isPlay = false
			return
		}
		audioManagerObj.playId = ""
		// 有网络就保存播放列表,设置标题
		if (await getNetworkType()) {
			setMpWxAdd(audioManagerObj.musicValue)
		}
		audioManagerObj.preValue = audioManagerObj.musicValue
		audioManagerObj.musicValue = ""
	}

}
// 微信小程序获取播放地址
async function setMpWxAdd(value : any) {
	ui.showLoading("象数音频制作中,请稍候..")
	return useCool().service.broadcast.record.miniBgAudio({ value }).then(async (res : any) => {
		ui.hideLoading()
		ui.showLoading("制作成功,象数音频加载中..")
		audioManagerObj.nanPlaySrc = await mpWxDownFile(tencentUrl + 'nan/' + res.playPath)
		audioManagerObj.nvPlaySrc = await mpWxDownFile(tencentUrl + 'nv/' + res.playPath)
		audioManager.src = audioManagerObj.sexual == "nan" ? audioManagerObj.nanPlaySrc : audioManagerObj.nvPlaySrc
		audioManagerObj.isPlay = true
		audioManagerObj.playId = res.info.id
		ui.hideLoading()
	}).catch((err) => {
		ui.showToast(err.message)
		ui.hideLoading()
	})
}
// 保存腾讯云音频到本地
function mpWxDownFile(url : any) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			success(res) {
				if (res.statusCode == 200) {
					resolve(res.tempFilePath)
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
}
// App播放音频
async function appPlayMusic() {
	// 如果正在播放，就暂停
	if (audioManagerObj.isPlay) {
		audioManager.pause()
		clearTimeout(audioManagerObj.bgAudioTime)
		audioManagerObj.isPlay = false
		if (audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == "·") {
			audioManagerObj.musicCurrent = 0
		}
		audioManagerObj.showAudioTime = setTimeout(() => {
			audioManagerObj.showAudio = false
		}, 10000)
	} else {
		if (audioManagerObj.musicValue == "" && audioManagerObj.musicValueArr.length == 0) {
			ui.showToast("没有正在播放的");
			return
		}
		// 播放广告
		rewardedFunction.value = 'adPlayMusic'
		let isAd = await isAdvertising()
		if (isAd == 0 || isAd == 2) {
			return
		}
		adPlayMusic()
	}
}
export async function adPlayMusic() {
	rewardedFunction.value = ""
	// 如果没在播放 musicValue也没值，代表暂停,继续播放
	if (audioManagerObj.musicValue == "") {
		music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
		audioManagerObj.musicCurrent++
		audioManagerObj.isPlay = true
	} else if (audioManagerObj.musicValueArr[audioManagerObj.musicCurrent] == "·") {
		// 如果点击后播放的是空白音频或者和上一个数相同，就从头播放 
		audioManagerObj.musicCurrent = 0
		music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
		audioManagerObj.musicCurrent++
		audioManagerObj.isPlay = true
	} else {
		// 如果musicValue有值，代表新修改的数字，要从头播放
		if (audioManagerObj.musicValue.length < 2) {
			ui.showToast("至少输入两位象数");
			audioManagerObj.isPlay = false
			return
		}
		// 有网络就保存播放列表,设置标题
		if (await getNetworkType()) {
			setRecord(audioManagerObj.musicValue)
		}
		setMusicValueArr(audioManagerObj.musicValue, false)
		audioManagerObj.musicValue = ""
	}
	audioManagerObj.showAudio = true
	clearTimeout(audioManagerObj.showAudioTime)
}
// 生成播放记录
export function setRecord(elephantNumber : string) {
	if (!elephantNumber) {
		return
	}
	let params = {
		elephantNumber,
	}
	// ui.showLoading()
	return useCool().service.broadcast.record.add(params).then((res : { recipeInfo : { name : string; }; id : string; }) => {
		// ui.hideLoading()
		audioManagerObj.playId = res.id
	})
}
// 保存musicValueArr的数据
export async function setMusicValueArr(item : string, showAd = true) {
	if (item.length < 2) {
		ui.showToast("至少输入两位象数");
		return
	}
	clearAudioManager()
	// 播放广告
	if (showAd) {
		rewardedFunction.value = "adMusicValueArr"
		rewardedFunctionItem.value = item
		let isAd = await isAdvertising()
		if (isAd == 0 || isAd == 2) {
			return
		}
	}
	adMusicValueArr(item)
}
export async function adMusicValueArr(item : any) {
	rewardedFunction.value = ""
	// #ifdef APP
	audioManagerObj.musicValueArr = [...item]
	audioManagerObj.musicValueArr.push("·")
	audioManagerObj.musicCurrent = 0
	music(audioManagerObj.musicValueArr[audioManagerObj.musicCurrent])
	audioManagerObj.musicCurrent++
	audioManagerObj.isPlay = true
	audioManagerObj.showAudio = true
	// #endif
	// #ifdef MP-WEIXIN
	// 有网络就保存播放列表,设置标题
	if (await getNetworkType()) {
		setMpWxAdd(item)
	}
	audioManagerObj.preValue = item
	// #endif
}
function music(number : any) {
	audioManager.src = `/static/${audioManagerObj.sexual}/${number}.mp3`
	audioManager.play()
}
// 暂停背景音频
export function stopAudioManager() {
	audioManager.pause()
	audioManagerObj.isPlay = false
	clearTimeout(audioManagerObj.bgAudioTime)
	audioManagerObj.bgAudioTime = 0
}
// 关闭背景音频
export function clearAudioManager() {
	audioManager.pause()
	audioManagerObj.musicValue = ""
	audioManagerObj.musicValueArr = []
	audioManagerObj.musicCurrent = 0
	audioManagerObj.isPlay = false
	clearTimeout(audioManagerObj.bgAudioTime)
	audioManagerObj.bgAudioTime = 0
}
// 试听音乐
export function trialListening(audioId : string, list : any) {
	let item = list.find(item => item.id == audioId)
	if (item?.url) {
		// 暂停正在播放的音乐
		stopAudioManager()
		audioManager.src = item.url
		audioManager.title = item.name ? item.name : '暂无名称';
		audioManager.singer = item.author ? item.author : '暂无';
		audioManager.coverImgUrl = item.cover ? item.cover : 'https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/wechat_option/logo.png';
	}
}
// 试听音乐
export function stopListening() {
	// if (audioManager&&audioManager.title != '象数助念器') {
		// console.log(222222,audioManager)
		audioManager.title = '象数助念器';
		audioManager.singer = '暂无';
		audioManager.coverImgUrl = 'https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/wechat_option/logo.png';
		audioManager?.stop()
	// }
}